package com.stars.easyms.datasource.mybatisplus;

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IKeyGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.core.injector.SqlRunnerInjector;
import com.baomidou.mybatisplus.core.toolkit.GlobalConfigUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.stars.easyms.base.util.ApplicationContextHolder;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;

/**
 * <p>className: EasyMsMybatisPlusGlobalConfig</p>
 * <p>description: MybatisPlus的GlobalConfig初始化类</p>
 *
 * @author guoguifang
 * @version 1.7.0
 * @date 2020/11/17 1:37 下午
 */
public class EasyMsMybatisPlusGlobalConfig {

    @PostConstruct
    public void init() {
        Configuration configuration = ApplicationContextHolder.getBean(Configuration.class);
        Assert.notNull(configuration, "org.apache.ibatis.session.Configuration instance is null!");
        GlobalConfig globalConfig = GlobalConfigUtils.getGlobalConfig(configuration);
        MetaObjectHandler metaObjectHandler = ApplicationContextHolder.getBean(MetaObjectHandler.class);
        if (metaObjectHandler != null) {
            globalConfig.setMetaObjectHandler(metaObjectHandler);
        }
        IKeyGenerator iKeyGenerator = ApplicationContextHolder.getBean(IKeyGenerator.class);
        if (iKeyGenerator != null) {
            globalConfig.getDbConfig().setKeyGenerator(iKeyGenerator);
        }
        ISqlInjector iSqlInjector = ApplicationContextHolder.getBean(ISqlInjector.class);
        if (iSqlInjector != null) {
            globalConfig.setSqlInjector(iSqlInjector);
        }
        IdentifierGenerator identifierGenerator = globalConfig.getIdentifierGenerator();
        if (identifierGenerator == null) {
            identifierGenerator = ApplicationContextHolder.getBean(IdentifierGenerator.class);
            if (identifierGenerator == null) {
                identifierGenerator = new DefaultIdentifierGenerator();
            }
            globalConfig.setIdentifierGenerator(identifierGenerator);
        }
        IdWorker.setIdentifierGenerator(identifierGenerator);
        if (globalConfig.isEnableSqlRunner()) {
            new SqlRunnerInjector().inject(configuration);
        }
        SqlSessionFactory sqlSessionFactory = ApplicationContextHolder.getBean(SqlSessionFactory.class);
        if (sqlSessionFactory != null) {
            globalConfig.setSqlSessionFactory(sqlSessionFactory);
        }
    }
}
